import { split, forEach } from 'lodash'

export const getUrlAllParams = (name?: string) => {
  const params:Record<string,any> = {};
  const url = decodeURI(window.location.href);
  const paramStrs = split(url, '?').length > 1 ? split(url, '?')[1] : '';
  forEach(paramStrs, item => {
    const param = split(item, '=')
    const key = param[0];
    const value = param[1]
    params[key] = value;
  })
  if (name) {
    return params[name];
  }
  return params
}

type TreeItem = {
  title?: string;
  value: string;
  children: TreeItem[]
}

export const flattenTree = (trees:TreeItem[], childrenKey = 'children') => {
  const flattenOptions:TreeItem[] = [];
  function dfs(nodes:any) {
    if (nodes === null && nodes.length === 0) {
      return
    }
    for (const node of nodes) {
      if (node) {
        flattenOptions.push(node)
      }
      if (node[childrenKey] && node[childrenKey].length > 0) {
        dfs(node[childrenKey])
      }
    }
  }
  dfs(trees)
  return flattenOptions
}